from fastapi import APIRouter, Query, Path, Body
from configs.response import APIResponse
from configs.pagination import Pagination
from apps.user import bodyForm
from apps.user import models
from apps.user import serializers

userApp = APIRouter(tags=["用户相关接口"])


@userApp.post("/login", summary="用户登录")
async def login(data: bodyForm.LoginForm = Body(...)):
    username = data.username
    password = data.password
    return APIResponse(code=200, message="ok", data={"token": ""}).response


@userApp.get("/users", summary="用户列表分页")
async def getUserList(
    page: int = Query(..., description="页码"),
    size: int = Query(..., description="每页条数"),
    search: str = Query(None, description="关键字"),
):
    queryset = models.User.all()
    # 初始化分页器
    pagination = Pagination(queryset, page=page, size=size)
    # 生成分页
    await pagination.general()
    page_ser = serializers.UserSerializer().get(pagination.queryset, many=True)
    data = {
        "data": page_ser,
        "page": pagination.page,
        "size": pagination.size,
        "total": pagination.total,
    }
    return APIResponse(code=200, message="ok", data=data).response


@userApp.post("/createUser", summary="创建用户信息")
async def createUser(data: bodyForm.UserForm = Body(...)):
    data = data.__dict__
    serializer = serializers.UserSerializer(data)
    user = await serializer.create()
    return APIResponse(code=200, message="ok", data=serializer.get(user)).response


@userApp.put("updateUser/{item_id}", summary="修改用户信息")
async def updateUser(
    item_id: int = Path(..., description="用户id"), data: bodyForm.UserForm = Body(...)
):
    data = data.__dict__
    serializer = serializers.UserSerializer(data)
    user = await serializer.update(item_id)
    return APIResponse(code=200, message="ok", data=serializer.get(user)).response


@userApp.delete("delUser/{item_id}", summary="删除用户信息")
async def delUser(item_id: int = Path(..., description="用户id")):
    serializer = serializers.UserSerializer()
    await serializer.delete(item_id)
    return APIResponse(code=200, message="ok").response
